<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/8/16
 * Time: 17:45
 * 收货地址
 */

namespace app\api\controller;

use app\common\controller\Api;
use fast\Auth;
use think\Db;

class Address extends Api {
	protected $noNeedRight = ['*'];
	
	public function index(){
		$userId = $this->auth->id;
		$rows = Db::name('address')->alias('a')
			->join('areas pa', 'a.province_id = pa.id', 'left')
			->join('areas ca', 'a.city_id = ca.id', 'left')
			->join('areas aa', 'a.area_id = aa.id', 'left')
			->where(['a.user_id' => $userId, 'status' => \app\common\model\Address::STATUS_Y])
			->field('a.id, a.is_default, a.province_id, pa.name as province, a.city_id, ca.name as city, a.area_id, aa.name as area, a.address, a.mobile, a.recipients')
			->select();
		$this->success(__('查询成功'), $rows);
	}
	
	public function edit(){
		$vali = new \app\common\validate\Address();
		$data = input('post.');
		$check = $vali->check($data);
		if(!$check){
			$this->error($vali->getError());
		}
		
		$data['user_id'] = $this->auth->id;
		$model = new \app\common\model\Address();
		if($data['id']) {
			$row = $model->find($data['id']);
			if(!$row) {
				$this->error(__('数据不存在'));
			}
			
			$res = $model->allowField(true)->save($data, ['id' => $data['id']]);
			if(!$res) {
				$this->error($model->getError());
			}
			$id = $data['id'];
			$message = __('修改成功');
		} else {
			$res = $model->allowField(true)->save($data);
			if(!$res) {
				$this->error($model->getError());
			}
			$message = __('添加成功');
			$id = $model->getLastInsID();
			
		}
		
		if($data['is_default']) {
			Db::name('address')->where('id', '<>', $id)->update(['is_default'  => 0]);
		}
		
		$this->success($message);
	}
	
	public function delete(){
		$id = input('post.id', '', 'int');
		$userId = $this->auth->id;
		
		$model = new \app\common\model\Address();
		$res = $model->save(['status' => $model::STATUS_D], [
			'id' => $id,
			'user_id' => $userId
		]);
		
		if($res !== false) {
			$this->success(__('删除成功'));
		}
		
		$this->error(__('删除出错'));
	}
	
	
}
